<?php
class Apps_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract {
	protected $_auth;
	protected $_acl;

	public function preDispatch(Zend_Controller_Request_Abstract $request) {
		$this->_auth = Zend_Auth::getInstance();

		if(($request->getParam('module') == 'admin')) {
			if($this->_auth->hasIdentity()) {
				$module 	 = $request->getParam('module');
				$controller  = $request->getParam ('controller');
				$action 	 = $request->getParam ('action');
				$resource 	 = $module . ' : ' . $controller;
				$groupId  	 = $this->_auth->getIdentity()->user_group_id;
				$tbUserGroup = new M_DbTable_UserGroup();
				$d	  	 	 = $tbUserGroup->fetchRow(array('id' => $groupId));
				$role 	 	 = $d['title'];

				$this->_acl  = new Apps_Acl($groupId);

				if (!$this->_acl->has($resource)) {
					$request->setModuleName('default');
					$request->setControllerName('error');
					$request->setActionName('error');
				} elseif(!$this->_acl->isAllowed($role, $resource, $action)) {
					// Role is
					if($this->_auth->hasIdentity()) {
						$request->setModuleName('admin');
						$request->setControllerName('auth');
						$request->setActionName('deny');
					}
				}
			} else {
				$request->setModuleName('default');
				$request->setControllerName('error');
				$request->setActionName('deny');
			}
		}
	}
}